<?php

namespace api\models;

use Yii;

class Book extends \common\models\Book
{
    private static $descLength = 0;
    public static function setDescLength($length){
        self::$descLength = intval($length);
    }

    public static function formatBookInfo($bookInfo){
        if(empty($bookInfo) || $bookInfo['id'] <= 0) return [];

        isset($bookInfo['id']) && $bookInfo['id'] = intval($bookInfo['id']);
        isset($bookInfo['author_id']) && $bookInfo['author_id'] = intval($bookInfo['author_id']);
        isset($bookInfo['category_id']) && $bookInfo['category_id'] = intval($bookInfo['category_id']);
        isset($bookInfo['over']) && $bookInfo['over'] = intval($bookInfo['over']);
        isset($bookInfo['status']) && $bookInfo['status'] = intval($bookInfo['status']);
        isset($bookInfo['add_time']) && $bookInfo['add_time'] = intval($bookInfo['add_time']);
        isset($bookInfo['nub']) && $bookInfo['nub'] = intval($bookInfo['nub']);

        if(self::$descLength > 0){
            if(isset($bookInfo['desc'])){
                $length = mb_strlen($bookInfo['desc']);
                if($length > self::$descLength){
                    $bookInfo['desc'] = mb_substr($bookInfo['desc'],0,self::$descLength).'...';
                }
            }
        }

        return $bookInfo;

    }

    public static function findById($id){
        return Book::findOne($id);
    }

    public static function formatBookList($books){
        $rs = [];
        foreach ($books as $bookInfo){
            $temp = self::formatBookInfo($bookInfo);
            $temp && $rs[] = $temp;
        }
        return $rs;
    }
    public static function randomBook($number = 10){
        $maxBookId = Book::find()->max('id');
        $randomIds = [];
        for($i = 0; count($randomIds) < $number; $i++){
            $rid = rand(1,$maxBookId);
            !in_array($rid,$randomIds) && $randomIds[] = $rid;
        }
        $books = Book::find()
            ->where(['status' => self::STATUS_OK])
            ->andWhere(['in','id',$randomIds])
            ->asArray()
            ->all();



        return self::formatBookList($books);
    }
}
